package br.ucb.cm.config.page.integration.ui;

import javax.swing.JPanel;
import javax.swing.BoxLayout;

import java.awt.BorderLayout;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
import java.util.ArrayList;
import java.util.List;

import javax.swing.JScrollPane;

import br.ucb.cm.config.bean.PieceConfig;
import javax.swing.border.LineBorder;

import java.awt.Color;
import javax.swing.ScrollPaneConstants;

public class Palette extends JPanel implements ItemListener{
	private static final long serialVersionUID = 1L;
	private List<PieceButton> piecePalette;

	public Palette(List<PieceConfig> pieces) {
		setBorder(new LineBorder(new Color(0, 0, 0)));
		setPieceList(pieces);
	}

	private List<PieceButton> mountArray(List<PieceConfig> pieces) {
		List<PieceButton> pp = new ArrayList<PieceButton>();

		if(pieces != null)
			for (PieceConfig piece : pieces)
				pp.add(new PieceButton(piece));

		return pp; 
	}

	private void initComponents() {
		setLayout(new BorderLayout(0, 0));

		JScrollPane scrollPane = new JScrollPane();
		scrollPane.setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_NEVER);
		add(scrollPane, BorderLayout.CENTER);

		JPanel panel = new JPanel();
		scrollPane.setViewportView(panel);
		panel.setLayout(new BoxLayout(panel, BoxLayout.X_AXIS));

		for (PieceButton piecePallete : this.piecePalette){
			piecePallete.addItemListener(this);
			panel.add(piecePallete);
		}
	}

	public PieceConfig getValue() {
		for (PieceButton palette : getPiecePalette()) 
			if (palette.isSelected()) 
				return palette.getPiece();

		return null;
	}


	public List<PieceButton> getPiecePalette() {
		return piecePalette;
	}

	public void setPiecePalette(List<PieceButton> pieces) {
		this.piecePalette = pieces;
	}

	@Override
	public void itemStateChanged(ItemEvent e) {
		PieceButton source = (PieceButton) e.getSource();

		if (source.isSelected()) {
			for (PieceButton palette : getPiecePalette())
				if (!palette.equals(source))
					palette.setSelected(false);
		}
	}

	public void setPieceList(List<PieceConfig> pieces) {
		removeAll();
		System.gc();
		
		piecePalette = mountArray(pieces);
		initComponents();
	}

}
